import md5 from 'blueimp-md5';
import WPT from 'wpt';

/**
 * 获取md5
 * @param {File|string} file
 * @param {*} callback
 */
export default function getMd5(file = '', callback) {
    return new Promise(resolve => {
        const done = result => {
            resolve(result);
            callback && callback(result);
        };

        // MD5失败返回空字符串
        const handleFail = msg => {
            done('');
            WPT.reportError({
                type: 'get-md5-fail',
                msg,
            });
        };

        const toMD5 = str => {
            // 避免md5失败
            try {
                done(md5(str));
            } catch (err) {
                handleFail(`md5 function error${err && err.message}`);
            }
        };

        if (file instanceof window.File) {
            if (window.FileReader) {
                const reader = new FileReader();
                reader.readAsDataURL(file);

                reader.addEventListener(
                    'load',
                    () => {
                        toMD5(reader.result);
                    },
                    false
                );

                // 避免获取读取文件失败
                reader.addEventListener('error', () => handleFail('read file error'));
                reader.addEventListener('abort', () => handleFail('read file abort'));
            } else {
                done('');
            }
        } else {
            toMD5(file);
        }
    });
}
